package online.zhangwenzhe.common.token;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
public class TokenController {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    //TODO: 需要增加expire从配置文件读取逻辑

    private int expire = 3600;

    @RequestMapping("common/token/generate")
    public String Generate() {
        String token = UUID.randomUUID().toString();
        Expiration expiration = Expiration.seconds(expire);
        redisTemplate.execute(new RedisCallback() {
            @Override
            public Integer doInRedis(RedisConnection connection) throws DataAccessException {
                connection.set(token.getBytes(), "".getBytes(), expiration, RedisStringCommands.SetOption.UPSERT);
                return 0;
            }
        });
        return token;
    }

    @RequestMapping("common/token/delete")
    public Long delete(@RequestParam String token) {
        Long result = redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                long result = 0;
                result = connection.del(token.getBytes());
                return result;
            }
        });
        return result;
    }
}
